package com.cm.dynamic.autoconfigure;

import com.cm.dynamic.classloader.factory.ClassLoaderFactory;
import com.cm.dynamic.classloader.factory.ClassLoaderFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.util.ObjectUtils;

/**
 * 动态执行器自动装配
 * @author xionglei
 * @version 1.0.0
 * 2021年08月25日 19:03
 */
@org.springframework.context.annotation.Configuration
@ConditionalOnClass({ClassLoaderFactory.class, ClassLoaderFactoryBean.class})
@ConditionalOnSingleCandidate(SqlSessionFactory.class)
@EnableConfigurationProperties({DynamicProperties.class})
@AutoConfigureAfter({WebMvcAutoConfiguration.class, MybatisAutoConfiguration.class})
public class DynamicAutoConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(MybatisAutoConfiguration.class);

    private final DynamicProperties properties;

    public DynamicAutoConfiguration(DynamicProperties properties) {
        this.properties = properties;
    }

    @Bean
    @ConditionalOnMissingBean
    public ClassLoaderFactory classLoaderFactory() throws Exception {
        ClassLoaderFactoryBean factory = new ClassLoaderFactoryBean();
        applyConfiguration(factory);
        if (!ObjectUtils.isEmpty(this.properties.getJarLocations())) {
            factory.setJarLocations(this.properties.getJarLocations());
        }
        if (!ObjectUtils.isEmpty(this.properties.getMapperLocations())) {
            factory.setMapperLocations(this.properties.getMapperLocations());
        }
        if (!ObjectUtils.isEmpty(this.properties.getBasePackages())) {
            factory.setBasePackages(this.properties.getBasePackages());
        }
        if (!ObjectUtils.isEmpty(this.properties.getMapperScanPackages())) {
            factory.setMapperScanPackages(this.properties.getMapperScanPackages());
        }
        return factory.getObject();
    }

    private void applyConfiguration(ClassLoaderFactoryBean factory) {
        Configuration configuration = this.properties.getConfiguration();
        if (configuration == null) {
            configuration = new Configuration();
        }
        factory.setConfiguration(configuration);
    }
}
